import { Component } from '@vue/runtime-core';
import { effect } from '@vue/reactivity';
import { createStore } from 'vuex';
import { getCartService } from '../api/cartApi';
import LayoutManager from '../layout/LayoutManager';
import Home from '../layout/Home.vue';

const $store = createStore({
  state: {
    layout: Home,
    userInfo: null,
    cartCount: 0,
  },
  mutations: {
    UPDATE_LAYOUT(state, layout) {
      state.layout = layout;
    },
    SETUP_USERINFO(state, uesrInfo) {
      state.userInfo = uesrInfo;
    },
    CLEAR_USERINFO(state) {
      state.userInfo = null;
    },
    SET_CART_COUNT(state, count) {
      state.cartCount = state.cartCount = count;
    },
  },
  actions: {
    updateLayout({ commit }, layout: Component) {
      commit('UPDATE_LAYOUT', layout);
    },
    setupUserInfo({ commit }, userInfo) {
      if (!localStorage.getItem('userInfo')) {
        try {
          localStorage.setItem('userInfo', JSON.stringify(userInfo));
        } catch (e) {
        }
      }
      commit('SETUP_USERINFO', userInfo);
    },
    clearUserInfo({ commit }) {
      commit('CLEAR_USERINFO');
      localStorage.removeItem('userInfo');
    },
    setCartCount({ commit }, count) {
      commit('SET_CART_COUNT', count);
    }
  },
  getters: {
    getUserInfo(store: any) {
      try {
        if (!store.userInfo && localStorage.getItem('userInfo')) {
          $store.dispatch('setupUserInfo', JSON.parse(localStorage.getItem('userInfo') || ''));
        }
      } catch (e) { }
      return store.userInfo;
    },
    getCartCount(store: any) {
      return store.cartCount;
    }
  }
});


effect(() => {
  $store.getters.getUserInfo && getCartService().then(res => {
    $store.dispatch('setCartCount', res?.data?.length || 0);
  });
})

export default $store;